import { defineStore } from 'pinia'
import { store } from '../index'
import { constantRoutes } from '@/router'
import menuList from '@/api/menu'
import { generateRoutesFn } from '@/router/routerHelper'

export const usePermissionStore = defineStore({
  id: 'permission',
  state: () => ({
    routers: [],
    addRouters: [],
    sidebarRouters: []
  }),
  getters: {
    getRouters() {
      return this.routers
    },
    getAddRouters() {
      return this.addRouters
    },
    getSidebarRouters() {
      return this.sidebarRouters
    }
  },
  actions: {
    // 生成路由
    generateRoutes() {
      return new Promise(resolve => {
        // 向后端请求路由数据
        const routerMap = generateRoutesFn(JSON.parse(JSON.stringify(menuList)))
        // 动态路由，404一定要放到最后面
        this.addRouters = routerMap.concat({
          path: '/:path(.*)',
          redirect: '/404',
          name: '404Page',
          meta: {
            hidden: true,
            breadcrumb: false
          }
        })
        // 渲染菜单的所有路由
        this.routers = [...constantRoutes].concat(routerMap)
        this.sidebarRouters = [...this.routers].filter((item) => !item?.meta?.hidden)
        resolve(this.addRouters)
      })
    }
  }
})

export const usePermissionStoreWithOut = () => {
  return usePermissionStore(store)
}
